package com.lin.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.utils.UIHandler;

import com.lin.activity.DynamicDetailActivity;
import com.lin.activity.DynamicShareWallActivity;
import com.lin.activity.FensiListActivity;
import com.lin.activity.FullScreenViewActivity;
import com.lin.activity.MyFensiListActivity;
import com.lin.activity.FocusListActivity;
import com.lin.activity.PersonalDetailCardActivity;
import com.lin.bean.PingLunBean;
import com.lin.bean.ZanList;
import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.Utils;
import com.lin.utils.Session.ResultReceiver;
import com.lin.utils.Session.ZanResult;
import com.lin.views.ListViewForFriendShare2;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.PinterestCircleBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.FriendsShareBean;
import com.yunfeng.supercall.bean.FriendsShareZanBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.manager.ShareManager;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler.Callback;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.internal.widget.AdapterViewCompat;
import android.support.v7.internal.widget.AdapterViewCompat.OnItemClickListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SuperFriendDynamicFragment extends Fragment  implements Constants, OnClickListener, ListViewForFriendShare2.OnItemListViewEventListener, PlatformActionListener, Callback, OnScrollListener{
	View mView;
	private ListViewForFriendShare2 mListView;
	Session mSession;
	private int mOtherId;

	private UserBean mUser;
	private View mHeaderView;
	private ImageView imageView;

	DisplayImageOptions options;
	ArrayList<SuperFriendsBean> mListFensi;
	ArrayList<SuperFriendsBean> mListGuanzhu;
	ArrayList<FriendsShareBean> mListFriendsShareBean;
	public static ArrayList<FriendsShareBean> mListFriendsShareBean2;
	private TextView mTextViewFensi;
	private TextView mTextViewFocus;
	int pagenum = 0;

	public static FriendsShareBean mShareBean;
	private TextView mTextViewUserName;
	private int userID;
	private LinearLayout mLinearLayout;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	private EditText mEditTextResponse;
	private Button mButtonReply;
	PingLunBean mPingLunBean;
	FriendsShareBean mCurrentShareBean;
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		
		
		options = new DisplayImageOptions.Builder()
		.displayer(new PinterestCircleBitmapDisplayer(getResources().getDimensionPixelSize(R.dimen.corners_avatar)))
		.showImageOnFail(R.drawable.bg_share_header)
		.showImageOnLoading(R.drawable.bg_share_header)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();


		Log.i("TAG", "onCreateView");

		mView = inflater.inflate(R.layout.fragment_friends_dynamic, null);


		mButtonReply = (Button) mView.findViewById(R.id.btn_send);
		mEditTextResponse = (EditText) mView.findViewById(R.id.et);
		mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipe);


		mSwipeRefreshLayout.setRefreshing(true);
		mSwipeRefreshLayout.setColorSchemeResources(R.color.base_orange);


		mHeaderView = inflater.inflate(
				R.layout.list_header_share_list, null);

		imageView = (ImageView) mHeaderView.findViewById(R.id.avatar);
		mTextViewFensi = (TextView) mHeaderView.findViewById(R.id.textview_fensi);
		mTextViewFocus = (TextView) mHeaderView.findViewById(R.id.textview_focus);
		mTextViewUserName = (TextView) mHeaderView.findViewById(R.id.user_name);
		mLinearLayout = (LinearLayout) mHeaderView.findViewById(R.id.ll);
		mListView = (ListViewForFriendShare2) mView.findViewById(R.id.listview);
		mListView.setOnScrollListener(this);

		mUser = BaseActivity.getUser(getActivity());
		mSession = Session.getSession();
		mSession.init(getActivity().getApplicationContext(), true);
		/*
		mSession.GetStore(getActivity(), mSession.getmUserBean().getUserid(), "1", "15",  new ResultReceiver<ArrayList<FriendsShareBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<FriendsShareBean> args) {
				// TODO Auto-generated method stub
			}
			
		}) ;*/


		
		userID = mOtherId = getArguments().getInt("USERDATA", 0);
		mOtherId = getArguments().getInt(KEY_DATA, 0);
		loadData(pagenum);
		if (mOtherId == -3) {
			mSession.getFriendDetailNew(getActivity().getApplicationContext(), userID, userID, new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean data) {
					// TODO Auto-generated method stub
					try {
						ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + data.getPhoto(), imageView, options);
					} catch(NullPointerException e) {

					}
				}
			});
			//			title.setText(R.string.enterprise_share);
		} else if (mOtherId == -2) {
			mSession.getFriendDetailNew(getActivity().getApplicationContext(), userID, userID, new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean data) {
					// TODO Auto-generated method stub
					try {
						ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + data.getPhoto(), imageView, options);
					} catch(NullPointerException e) {

					}
				}
			});
			//			title.setText(R.string.focused_share);
		} else if (mOtherId == -1) {
			mSession.getFriendDetailNew(getActivity().getApplicationContext(), userID, userID, new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean data) {
					// TODO Auto-generated method stub
					try {
						ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + data.getPhoto(), imageView, options);
					} catch(NullPointerException e) {

					}
				}
			});
			//			title.setText(R.string.fans_share);
		} else  {
			if(mOtherId == mUser.getUserid()) {
				//				mTextViewUserName.setText(mUser.getNick_name());
			}
			if(mOtherId != 0) {
				mSession.getFriendDetailNew(getActivity().getApplicationContext(), mOtherId, mOtherId, new ResultReceiver<SuperFriendsBean>() {

					@Override
					public void onResult(boolean last, SuperFriendsBean data) {
						// TODO Auto-generated method stub
						try {
							mTextViewUserName.setText(data.getNick_name());
						} catch (NullPointerException e) {
							mTextViewUserName.setText(mUser.getNick_name());
						}

						try {
							ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + data.getPhoto(), imageView, options);
						} catch(NullPointerException e) {
							ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mUser.getPhoto(), imageView, options);
						}
					}
				});
			} else { //0 为超友墙
				mLinearLayout.setVisibility(View.GONE);
				mSession.getFriendDetailNew(getActivity().getApplicationContext(), mUser.getUserid(), mUser.getUserid(), new ResultReceiver<SuperFriendsBean>() {

					@Override
					public void onResult(boolean last, SuperFriendsBean data) {
						// TODO Auto-generated method stub
						try {
							mTextViewUserName.setText(data.getNick_name());
						} catch(NullPointerException e) {
							mTextViewUserName.setText(mUser.getNick_name());
						}
						try {
							ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + data.getPhoto(), imageView, options);
						} catch(NullPointerException e) {
							ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mUser.getPhoto(), imageView, options);

						}
					}
				});
			}
			mListView.addHeaderView(mHeaderView);
			mTextViewFensi.setOnClickListener(this);
			mTextViewFocus.setOnClickListener(this);
		} /*else {
			mListView.addHeaderView(mHeaderView);
			mTextViewFensi.setOnClickListener(this);
			mTextViewFocus.setOnClickListener(this);
			if(mOtherId == mUser.getUserid()) {
				mTextViewUserName.setText(mUser.getNick_name());
			}
			String avatar = BaseActivity.getUser(getActivity().getApplicationContext()).getPhoto();

			ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + avatar, imageView, options);
		}
		 */

		/*	
		mSession.getShareList(getActivity().getApplicationContext(), 0, mOtherId, new ResultReceiver<ArrayList<FriendsShareBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<FriendsShareBean> data) {
				// TODO Auto-generated method stub
				mListView.setDataList(data);
				mListFriendsShareBean = data;
			}

		});*/

		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
             public void onScrollStateChanged(AbsListView absListView, int i) {
 
        }
 
            @Override
             public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            	mSwipeRefreshLayout.setEnabled(false);
                if (firstVisibleItem == 0)
                	mSwipeRefreshLayout.setEnabled(true);
                else
                	mSwipeRefreshLayout.setEnabled(false);
        }
    });

		imageView.setOnClickListener(this);
		mListView.setOnItemListViewEventListener(this);
		mButtonReply.setOnClickListener(this);
		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pagenum = 0;
				loadShareList(pagenum);
			}
		});
		return mView;
	}



	private void loadData(int pagenum) {
		mSession.getFensiList(getActivity(), pagenum, mOtherId, new ResultReceiver<ArrayList<SuperFriendsBean>>() {

			@Override
			public void onResult(boolean last,
					ArrayList<SuperFriendsBean> data) {
				// TODO Auto-generated method stub
				if(data == null) return;
				mListFensi = data;
				mTextViewFensi.setText("粉丝:" + mListFensi.size());
			}

		});
		mSession.getGuanzhuList(getActivity(), 0, mOtherId, new ResultReceiver<ArrayList<SuperFriendsBean>>() {

			@Override
			public void onResult(boolean last,
					ArrayList<SuperFriendsBean> data) {
				// TODO Auto-generated method stub
				if(data == null) return;
				mListGuanzhu = data;
				mTextViewFocus.setText("关注:" + mListGuanzhu.size());
			}

		});
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == mTextViewFocus) {
			Intent intent = new Intent(getActivity(), FocusListActivity.class);
			intent.putExtra("data", mOtherId);
			startActivity(intent);
		} else if(v == mTextViewFensi) {
			Intent intent = new Intent(getActivity(), FensiListActivity.class);
			intent.putExtra("data", mOtherId);
			startActivity(intent);
		} else if(v == imageView) {
			Session mSession = Session.getSession();
			mSession.init(getActivity(), true);
			mSession.getFriendDetailNew(getActivity(), mOtherId, mOtherId, new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean data) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(), PersonalDetailCardActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("data", data);
					startActivity(intent);		
				}
			});
		} else if(v == mButtonReply) {
			String  content = mEditTextResponse.getText().toString();
			if(TextUtils.isEmpty(content)) {
				Toast.makeText(getActivity(), "请输入回复内容", Toast.LENGTH_SHORT).show();
				return ;
			}
			
			// TODO Auto-generated method stub
			mSession.setPinglunReply(getActivity(), mSession.getmUserBean().getUserid() + "", mCurrentShareBean.getShareid() + "", content, mSession.getmUserBean().getLat() + "", mSession.getmUserBean().getLng() + "", mPingLunBean.getReplyid() + "", new ResultReceiver<Integer>() {

				@Override
				public void onResult(boolean last, Integer args) {
					// TODO Auto-generated method stub
					
				}
				
			});
		}
	}
	@Override
	public void onItemAvatarLisener(FriendsShareBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(getActivity(), DynamicShareWallActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra(KEY_DATA, maListInfo.getUserid());
		intent.putExtra("avatar", maListInfo.getPhoto());
		intent.putExtra("username", maListInfo.getNick_name());
		startActivity(intent);

	}
	@Override
	public void onItemClickListener(FriendsShareBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub
		mListFriendsShareBean2 = mListFriendsShareBean;
		mShareBean = maListInfo;
		Intent intent = new Intent(getActivity(), DynamicDetailActivity.class);
		startActivity(intent);
	}
	@Override
	public void onItemUserDetailListener(FriendsShareBean maListInfo, int x,
			int y) {
		// TODO Auto-generated method stub
		mListFriendsShareBean2 = mListFriendsShareBean;
		mShareBean = maListInfo;
		Intent intent = new Intent(getActivity(), DynamicDetailActivity.class);
		startActivity(intent);
	}
	@Override
	public void onItemGridViewClickListener(FriendsShareBean maListInfo,
			int position) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);

		intent.putParcelableArrayListExtra("datalist", mListFriendsShareBean);
		int index = mListFriendsShareBean.indexOf(maListInfo);
		intent.putExtra("dataitem", index);
		intent.putExtra("position", position);
		startActivity(intent);

	}

	@Override
	public void onItemProClickListener(final FriendsShareBean maListInfo, int x, int y) {
		// TODO Auto-generated method stub

		mSession.addShareZan(getActivity(), mUser.getUserid(), maListInfo.getShareid(), new ResultReceiver<ZanResult>() {

			@Override
			public void onResult(boolean last, ZanResult result) {
				// TODO Auto-generated method stub
				if(result == ZanResult.SUCCESS) {
					maListInfo.setZannum(Integer.parseInt(maListInfo.getZannum()) + 1 + "");

					if(maListInfo.getmZanList() == null) maListInfo.setmZanList(new ArrayList<ZanList>());
					if(!maListInfo.getmZanList().contains(new ZanList(mUser.getNick_name(), mUser.getPhoto()))) {


						try {
							maListInfo.getmZanList().add(new ZanList(mUser.getNick_name(), mUser.getPhoto()));

						} catch(NullPointerException e) {
							ArrayList<ZanList> arrayList = new ArrayList<ZanList>();
							maListInfo.setmZanList(arrayList);
							maListInfo.getmZanList().add(0, new ZanList(mUser.getNick_name(), mUser.getPhoto()));
						}
						mListView.setDataList(mListFriendsShareBean);
						Toast.makeText(getActivity(), "点赞成功", Toast.LENGTH_SHORT).show();
					} else {
						maListInfo.getmZanList().remove(new ZanList(mUser.getNick_name(), mUser.getPhoto()));
						int num = Integer.parseInt(maListInfo.getZannum());
						maListInfo.setZannum(( num - 2) + "");
						mListView.setDataList(mListFriendsShareBean);

						Toast.makeText(getActivity(), "取消成功", Toast.LENGTH_SHORT).show();
					}
				}
			}

		});
		//		View content = getActivity().getLayoutInflater().inflate(R.layout.dialog_share, null);
		//		Dialog mDialog = DevBaseActivity.getDialog(
		//				getActivity(), content, null);
		//		setUpImage(content);
	}

	/*private void setUpImage(View v) {
		if (v instanceof ImageView) {
			v.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					int img = v.getId();
					if (img == R.id.weibo) {
						ShareManager.shareToWeiBo(getActivity());
					} else if (img == R.id.wechat_circle) {
						int userid = BaseActivity.getUser(getActivity()).getUserid();
						Utils.shareWechatCircle(getActivity(), SuperFriendDynamicFragment.this, userid);
					} else if (img == R.id.wechat_friends) {
						int userid = BaseActivity.getUser(getActivity()).getUserid();
						Utils.shareWechatToFriends(getActivity(),SuperFriendDynamicFragment.this, userid);
					} else if (img == R.id.qq) {
						ShareManager.shareToQQ(getActivity());
					} else if (img == R.id.sms_share){
						int userid = BaseActivity.getUser(getActivity()).getUserid();
						Utils.sendSMS(getActivity(), getResources().getString(R.string.sms_share, userid));
					}
				}
			});
		} else if (v instanceof ViewGroup) {
			for (int i = 0; i < ((ViewGroup) v).getChildCount(); i++) {
				setUpImage(((ViewGroup) v).getChildAt(i));
			}
		}
	}*/




	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mListView.setDataList(mListFriendsShareBean);

		loadShareList(pagenum);

	}



	
	private void loadShareList(int pagenum) {
		mSession.getShareListNew(getActivity().getApplicationContext(), mUser.getUserid(), mOtherId, 3, 25, pagenum,new ResultReceiver<ArrayList<FriendsShareBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<FriendsShareBean> data) {
				// TODO Auto-generated method stub
				mSwipeRefreshLayout.setRefreshing(false);

				if(data != null && data.size() > 0) {
					Log.i("SuperCall", data.size() + "");
					mListView.setDataList(data);
					mListFriendsShareBean = data;
					
					DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getActivity(), "db", 2);
					mDatabaseHelperForChattingMap.insertFriendsShareBeanList(data, mUser.getUserid() + "", mOtherId + "");
					if(mDatabaseHelperForChattingMap != null) {
						mDatabaseHelperForChattingMap.close();
						mDatabaseHelperForChattingMap = null;
					}
				} else {
					DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getActivity(), "db", 2);
					ArrayList<FriendsShareBean> mListFriendsShareBean = mDatabaseHelperForChattingMap.getFriendsShareBeanList(mUser.getUserid() + "", mOtherId + "");
					if(mDatabaseHelperForChattingMap != null) {
						mDatabaseHelperForChattingMap.close();
						mDatabaseHelperForChattingMap = null;
					}
					
					mListView.setDataList(mListFriendsShareBean);
				}
			}

		});
	}
	@Override
	public void onCancel(Platform arg0, int arg1) {
		Message msg = new Message();
		msg.what = 0;
		UIHandler.sendMessage(msg, this);
	}

	@Override
	public void onComplete(Platform plat, int action,
			HashMap<String, Object> res) {
		Message msg = new Message();
		msg.arg1 = 1;
		msg.arg2 = action;
		msg.obj = plat;
		UIHandler.sendMessage(msg, this);
	}

	@Override
	public void onError(Platform arg0, int arg1, Throwable arg2) {
		Message msg = new Message();
		msg.what = 1;
		UIHandler.sendMessage(msg, this);
	}
	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		int what = msg.what;
		if (what == 1) {
			Toast.makeText(getActivity(), "分享失败", Toast.LENGTH_SHORT).show();
		}
		return false;
	}
	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		switch (scrollState) {
		// 当不滚动时
		case OnScrollListener.SCROLL_STATE_IDLE:
			// 判断滚动到底部
			if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
				pagenum++;
				loadShareList(pagenum);
				Toast.makeText(getActivity(), "正在加载新数据", Toast.LENGTH_SHORT).show();
			}
			break;
		}	
	}



	@Override
	public void onItemCollectionClickListener(FriendsShareBean maListInfo,
			int x, int y) {
		// TODO Auto-generated method stub
		

		
		mSession.SetStore(getActivity(), mSession.getmUserBean().getUserid() + "", maListInfo.getShareid() + "", new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub
				if(args == 1) {
				Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
				}else if(args == 0) {
					Toast.makeText(getActivity(), "已经收藏", Toast.LENGTH_SHORT).show();	
				}else if(args == -1) {
					Toast.makeText(getActivity(), "没有网络", Toast.LENGTH_SHORT).show();	
				}
			}
			
		}) ;
	}





	@Override
	public void onItemListViewCommentClickListener(
			FriendsShareBean friendsShareBean, PingLunBean maListInfo,
			int position) {
		// TODO Auto-generated method stub
		mEditTextResponse.setHint("回复:" + friendsShareBean.getNick_name());
		mEditTextResponse.setFocusable(true);
		mPingLunBean = maListInfo;		
		mCurrentShareBean = friendsShareBean;
	}


	


}